from flask import Flask, Blueprint, request, redirect, url_for, flash, current_app, render_template
from datetime import datetime
import os
from app.config import create_db_connection
from app.config import compress_and_save_image


add_product_bp = Blueprint('add_product', __name__)


@add_product_bp.route('/add_product')
def add_product():
    try:
        conn, cursor = create_db_connection()

        # 获取客户列表
        cursor.execute('SELECT * FROM customer_list')
        customer_list = cursor.fetchall()

        # 获取分类列表
        cursor.execute('SELECT * FROM class_list')
        class_list = cursor.fetchall()

    except Exception as e:
        current_app.logger.error(f"Something went wrong: {str(e)}")
        flash("数据库操作失败，请稍后再试或联系管理员。")
        customer_list, class_list = [], []
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

    return render_template('product/add_product.html', customer_list=customer_list, class_list=class_list)



# 定义上传文件夹的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, '../static/data/product_img')
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 检查文件夹是否存在，如果不存在，则创建
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@add_product_bp.route('/submit_prod', methods=['POST'])
def submit_prod():
    try:
        file = request.files.get('productImage')
        customer_id = request.form.get('customer_id')
        class_id = request.form.get('class_id')
        product_name = request.form.get('productName')
        product_model = request.form.get('productModel')
        product_color = request.form.get('productColor')
        product_unit = request.form.get('productUnit')
        purchase_price = request.form.get('purchasePrice')
        sales_price = request.form.get('salesPrice')

        if not customer_id:
            flash('请选择产品所属公司', 'error')
            return redirect('/add_product')

        if file:
            if allowed_file(file.filename):
                timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
                _, file_extension = os.path.splitext(file.filename)
                filename = f"{timestamp}{file_extension}"
                file_path = os.path.join(UPLOAD_FOLDER, filename)

                # 压缩并保存图片
                compress_and_save_image(file, file_path)

                # 创建相对路径用于数据库保存
                relative_path = 'data/product_img/' + filename
            else:
                flash('产品图片为不支持的文件类型', 'error')
                return redirect('/add_product')
        else:
            relative_path = 'img/Default_image.png'

        conn, cursor = create_db_connection()

        # 检查是否存在重复记录
        check_duplicate_query = '''
        SELECT id 
        FROM product_list 
        WHERE customer_id = %s AND product_name = %s AND product_model = %s AND product_color = %s
        '''
        cursor.execute(check_duplicate_query,
                       (customer_id, product_name, product_model, product_color))
        duplicate_record = cursor.fetchone()

        if duplicate_record:
            flash('该产品已存在', 'error')
            return redirect('/add_product')

        if not product_name or not product_name.strip():
            flash('产品名称不能为空!', 'error')
            return redirect('/add_product')

        if not product_unit or not product_unit.strip():
            product_unit = "PCS"

        if not purchase_price or not purchase_price.replace('.', '').isdigit():
            purchase_price = 0
        else:
            purchase_price = float(purchase_price)

        if not sales_price or not sales_price.replace('.', '').isdigit():
            sales_price = 0
        else:
            sales_price = float(sales_price)

        # 插入新的产品记录
        insert_query = '''
        INSERT INTO product_list (customer_id, class_id, product_name, product_model, product_color, 
                                  product_unit, purchase_price, sales_price, image_path) 
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        '''
        values = (
            customer_id, class_id, product_name, product_model, product_color, product_unit,
            purchase_price, sales_price, relative_path
        )
        cursor.execute(insert_query, values)

        conn.commit()

    except Exception as e:
        current_app.logger.error(f"Something went wrong: {str(e)}")
        flash('添加产品失败', 'error')
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

    flash('添加产品成功')
    return redirect('/add_product')
